<template>
  <div ref="EcharRef" class="monitorContainer" />
</template>

<script setup>
import * as echarts from 'echarts';
import { onMounted, onUnmounted, nextTick, watch, ref } from 'vue';

// 定义 props
const props = defineProps({
  chartOption: {
    type: Object,
    default: () => ({
      seriesData: []
    })
  }
});

// DOM 引用
const EcharRef = ref(null);
let myChart = null;

// 初始化并设置图表
const setOption = async () => {
  await nextTick();

  if (!EcharRef.value) {
    console.warn('Chart container ref is not available');
    return;
  }

  // 检查 DOM 尺寸
  const { offsetWidth, offsetHeight } = EcharRef.value;
  if (offsetWidth <= 0 || offsetHeight <= 0) {
    console.warn('Chart container has no width or height:', { width: offsetWidth, height: offsetHeight });
    return;
  }

  // 如果已有实例，先销毁
  if (myChart) {
    myChart.dispose();
  }

  myChart = echarts.init(EcharRef.value);

  // 验证数据格式
  const validData = Array.isArray(props.chartOption.seriesData) 
    ? props.chartOption.seriesData 
    : [];

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}<br />总占比：{d}%',
      backgroundColor: '#FFFFFF',
      borderColor: '#eef3f8',
      borderWidth: 1,
      textStyle: {
        color: '#8C8C8C',
      },
      padding: 12,
    },
    label: {
      formatter: ['{name|{b}}', '{percentage|{d}%}'].join('\n'),
      rich: {
        name: {
          color: '#333333',
          fontWeight: 'bolder',
          align: 'left',
        },
        percentage: {
          color: '#000000',
          lineHeight: 15,
          align: 'left',
        },
      },
    },
    labelLine: {
      lineStyle: {
        color: '#BFBFBF',
      },
    },
    series: [
      {
        type: 'pie',
        roseType: 'radius',
        radius: [33, 100],
        center: ['50%', '50%'],
        data: validData,
        animationEasing: 'cubicInOut',
        animationDuration: 2600,
      },
    ],
    color: ['#85A7FF', '#99EBBD', '#FFB18B', '#C6EBFF', '#BECCE6'],
  };

  myChart.setOption(option);

  // 自适应窗口大小
  window.addEventListener('resize', handleResize);
};

// 窗口 resize 处理
const handleResize = () => {
  myChart?.resize();
};

// 组件挂载后初始化
onMounted(() => {
  setOption();
});

// 监听 chartOption 变化，自动更新图表
watch(
  () => props.chartOption,
  () => {
    if (myChart) {
      setOption();
    }
  },
  { deep: true }
);

// 组件卸载前销毁实例
onUnmounted(() => {
  if (myChart) {
    window.removeEventListener('resize', handleResize);
    myChart.dispose();
    myChart = null;
  }
});
</script>

<style lang="scss" scoped>
.monitorContainer {
  width: 100%;
  height: 300px;

  & > div,
  & > canvas {
    width: 100% !important;
    height: 100% !important;
  }
}
</style>
